package com.lagou.lagouservicecode.controller;

import com.lagou.lagouservicecode.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @Authther: mrwu
 * @date:2021/4/14-04
 * @Description:com.lagou.lagouservicecode.controller
 */
@RestController
public class CodeController {
    static final String CODE_PRI_FIX ="mailcode:";
    @Autowired
    DiscoveryClient discoveryClient;
    //使用feign进行服务调用
    @Autowired
    MailService mailService;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    //生成验证码
    @GetMapping("/code/{email}")
    public Boolean sendCode(@PathVariable(name = "email") String email){
        ValueOperations opsForValue = redisTemplate.opsForValue();//字符串操作连接
        //先从缓存中取出数据//如果有，直接返回，如果没有调用下游服务
        Object o = opsForValue.get(CODE_PRI_FIX + email);
        if (o ==null){
          //生成验证验证码
        }
        boolean result = mailService.sendCode(email, "123456");
        if (result){
            //将验证码存入redis
            opsForValue.set(CODE_PRI_FIX+email, "123456", 10, TimeUnit.MINUTES);//设置10分钟超时
        }
        return result;
    }

    /**
     * 被feign 调用需要显示声明参数绑定关系
     * @param eamil
     * @param code
     * @return
     */
    @GetMapping("/code/validate")
    public Boolean isValite(@RequestParam("email") String eamil,@RequestParam("code") String code){

        //从redis中取出数据和code进行对比
        ValueOperations opsForValue = redisTemplate.opsForValue();//字符串操作连接
        String result =(String) opsForValue.get(CODE_PRI_FIX + eamil);
        if (result==null){
            return false;
        }
        return result.equals(code);
    }

}
